package com.github.niefy.modules.wx.bean;

import java.io.IOException;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

import com.google.gson.Gson;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;

@Slf4j
@Setter
public class CloudWxMpServiceImpl extends WxMpServiceHttpClientImpl {

	private String accessTokenUrl;

	private final Gson gson = new Gson();

	@SuppressWarnings("unchecked")
	@Override
	public String getAccessToken(boolean forceRefresh) throws WxErrorException {

		final WxMpConfigStorage config = this.getWxMpConfigStorage();

		String url = String.format(this.accessTokenUrl, config.getAppId());
		try {
			HttpGet httpGet = new HttpGet(url);
			if (this.getRequestHttpProxy() != null) {
				RequestConfig requestConfig = RequestConfig.custom().setProxy(this.getRequestHttpProxy()).build();
				httpGet.setConfig(requestConfig);
			}
			try (CloseableHttpResponse response = getRequestHttpClient().execute(httpGet)) {
				String responseBody = new BasicResponseHandler().handleResponse(response);
				if (log.isInfoEnabled()) {
					log.info("获取cloud的accessToken接口返回->{}", responseBody);
				}
				Map<String, Object> result = gson.fromJson(responseBody, Map.class);
				Object object = result.get("data");
				return (String) object;
			} finally {
				httpGet.releaseConnection();
			}
		} catch (IOException e) {
			throw new WxRuntimeException(e);
		}
	}
}
